package com.itheima.aspect;

import com.alibaba.fastjson.JSON;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component      //将该类对象交给IOC容器管理
@Aspect         //标识该类是一个切面类
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    // @Before("execution(* com.itheima.service.*.*(..))")
    /*@Before("@annotation(com.itheima.aspect.MyLog)")
    public void before(){
        System.out.println("前置通知....");
    }*/

    @Around("@annotation(com.itheima.aspect.MyLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("环绕前置通知...");

        //将操作记录日志插入到数据库表中
        OperateLog operLog = new OperateLog();
        //构造日志信息

        //获取当前登录用户的id【从请求头中获取】
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        operLog.setOperateUser((Integer) claims.get("id"));      //操作人

        operLog.setOperateTime(LocalDateTime.now());
        operLog.setClassName(joinPoint.getTarget().getClass().getName());
        operLog.setMethodName(joinPoint.getSignature().getName());
        operLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));

        //记录方法开始时间
        long begin = System.currentTimeMillis();
        //运行原始方法,获取到返回值
        Object obj = joinPoint.proceed();
        //记录方法结果时间
        long end = System.currentTimeMillis();
        operLog.setReturnValue(JSON.toJSONString(obj));
        operLog.setCostTime(end - begin);

        //将对象插入到数据库
        operateLogMapper.insert(operLog);

        log.info("环绕后置通知...");
        return obj;
    }
}
